package com.fingard.dsp.bank.directbank.nccb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 江西银行
 */
public class NCCB01Base extends DirectBase implements ITcpClient {

    protected String reqTime = "";

    private static TransIDHelper idHelper = new TransIDHelper(1, 999999999);

    protected void writeCommonHeader(XmlTextWriter xmlWriter, NCCB01Header header) throws Exception {
        if (StringHelper.isNullOrEmpty(header.transCode)) {
            throw new Exception("未赋值transCode");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("HttpUserId",  "910017");
        xmlWriter.writeElementString("HttpOtherJnlNo",  header.serialNo);
        xmlWriter.writeElementString("HttpReqTime",Format.DateTime14Format.format(new Date()));
        xmlWriter.writeEndElement();
    }

    private boolean addCstNo(String bsnCode) {
        return "CBE004".equals(bsnCode) || "CBE005".equals(bsnCode) || "CBE006".equals(bsnCode) ||"CBE007".equals(bsnCode) || "CBE008".equals(bsnCode)
                || "CBE009".equals(bsnCode) || "CBE011".equals(bsnCode);
    }

    protected String[] sendToBank(String p_reqStr, NCCB01Header header) throws Exception {
        String[] retStr = new String[]{"", ""};

        String tmpUrl = bankFront.serverURL + header.transCode + "?userPassword=123456&SIGDATA="+header.msgType;
        WriteBankLogLn("1.提交银行的地址：" + tmpUrl);
        //构造请求规范
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/stream");
        tmpWebRequest.setRequestProperty("Accept", "text/directxml");
        tmpWebRequest.setRequestProperty("User-Agent", "NCCB_DIRECTBANK/1.0");
        //tmpWebRequest.setRequestProperty("connection", "Close");
        String charsetName = "UTF-8";
        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpToWriteBytes, "UTF-8");
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    //进行签名
    protected String signature(String data) throws Exception {
        String signURL = bankFront.signURL;
        WriteBankLogLn("1.银行签名地址：" + signURL);
        WriteBankLogStep2(data);
        String signedData = "";
        WebRequest tmpWebRequest = new WebRequest(signURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Length", String.valueOf(data.length()));
        tmpWebRequest.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = data.getBytes(charsetName);
        String[] retSign = tmpWebRequest.upload(tmpToWriteBytes,"UTF-8");

        if (retSign[0].length() == 0) {
            try {
                WriteBankLogLn("3.签名返回的结果：" + retSign[1]);
                XmlTextReader tmpXmlReader = new XmlTextReader(retSign[1]);
                String tmpRest = tmpXmlReader.getSimpleText("result");
                if ("0".equals(tmpRest)) {
                    WriteBankLogLn("签名成功");
                    signedData = tmpXmlReader.getSimpleText("sign");
                } else {
                    WriteBankLogLn("签名失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                WriteBankLogLn(e.getMessage());
            }

        } else {
            WriteBankLogLn("与银行签名端口通讯失败；详细信息：" + retSign[1]);
        }
        return signedData;
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }
    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {

    }

    protected String getTrmSeqNum() {
        Date tmpDateNow = new Date();
        return Format.Date8Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected  String timestampToDate(String timestamp){
        if(StringHelper.isNullOrEmpty(timestamp)){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date(Long.parseLong(timestamp))).substring(11,19); // 时间戳转换日期
        return dateStr;
    }
    /**
     * 获取子账号序号
     * @param account
     * @return
     */
    protected  String getSonSeq(String account){
        String sonSeq = "";
        if(account == null){
            return sonSeq;
        }
        if(account.length()>3){
            sonSeq ="0" + account.substring(account.length()-3,account.length());
        }
        return sonSeq;
    }
}
